package org.jpass.dc.view.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.jpass.dc.business.admin.bean.AdminBean;
import org.jpass.dc.business.admin.logic.AdminLogic;
import org.jpass.dc.common.bean.Page;
import org.jpass.dc.common.exception.ApplicationException;
import org.jpass.dc.common.util.Encrypter;
import org.jpass.dc.common.util.RefParaValue;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AdminAction extends ActionSupport {
	private static final long serialVersionUID = 1L;

	private String name;
	private String realName;
	private String password;
	private String rePassword;
	private Integer authority;
	private String notes;
	private AdminBean adminBean = new AdminBean();
	private AdminLogic adminLogic = new AdminLogic();

	/** 管理员登录 **/
	public String login() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(ServletActionContext.HTTP_REQUEST);
		try {
			if (!RefParaValue.empty(name) && !RefParaValue.empty(password)) {
				AdminBean onlineAdmin = adminLogic.login(name, password);
				ctx.getSession().put("user", onlineAdmin); // 往session添加当前管理员
				request.setAttribute("admin", onlineAdmin);
				return Action.SUCCESS;
			} else {
				return Action.ERROR;
			}
		} catch (ApplicationException e) {
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
	}

	/** 创建管理员 **/
	public String addAdmin() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		AdminBean onlineAdmin = (AdminBean) ctx.getSession().get("user");
		String level = request.getParameter("levelValue");
		String authorityName = "";
		switch (Integer.parseInt(level)) {
		case 1:
			authorityName = "高级管理员";
			break;
		case 2:
			authorityName = "中级管理员";
			break;
		case 3:
			authorityName = "普通管理员";
			break;
		}
		try {
			if (!RefParaValue.empty(onlineAdmin)) {
				adminBean.setPassword(Encrypter.md5Encrypt(adminBean.getPassword()));
				adminBean.setAuthority(Integer.parseInt(level));
				adminBean.setAuthorityName(authorityName);
				adminBean.setCreater(onlineAdmin.getName());
				adminBean.setCreatedTime(new Date());
				adminBean.setIsOnline(0);
				adminBean.setLoginTimes(0);
				boolean result = adminLogic.addAdmin(adminBean);
				if (result) {
					this.writeReturnMsg("{'success':true}");
				}
			}
		} catch (ApplicationException e) {
			this.writeReturnMsg("{'success':false, 'msg':'" + e.getMessage() + "' , 'type':'error'}");
		}
		return null;
	}

	/**删除管理员**/
	public String deleteAdmin() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String deleteIds = request.getParameter("deleteIds");
		try{
			adminLogic.deleteAdmin(deleteIds);
			this.adminManage();
		}catch(ApplicationException e){
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	} 
	
	/** 返回管理员修改密码信息 **/
	public String updateMyPassForm() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String id = request.getParameter("id");
		try {
			if (!RefParaValue.empty(id)) {
				AdminBean admin = adminLogic.findAdminById(id);
				request.setAttribute("admin", admin);
				return Action.SUCCESS;
			}
		} catch (ApplicationException e) {
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
		return null;
	}
	
	/** 管理员修改个人密码 **/
	public String updateMyPass() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String id = request.getParameter("id");
		String oldPassword = request.getParameter("oldPassword");
		String password = request.getParameter("password");
		try {
			if (!RefParaValue.empty(id)) {
				adminLogic.updatePass(id,oldPassword, password);
				this.writeReturnMsg("{'success':true}");
			}
		} catch (ApplicationException e) {
			this.writeReturnMsg("{'success':false, 'msg':'" + e.getMessage()
					+ "' , 'type':'error'}");
		}
		return null;
	}

	/** 返回管理员信息 **/
	public String adminInfo() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		String adminId = request.getParameter("id");
		try {
			AdminBean admin = adminLogic.findAdminById(adminId);
			if (!RefParaValue.empty(admin)) {
				request.setAttribute("admin", admin);
			}
		} catch (ApplicationException e) {
			request.setAttribute("tip", e.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	}

	/** 修改管理员信息 **/
	public String updateAdminInfo() throws Exception {
		try {
			AdminBean admin = adminLogic.updateAdminInfo(adminBean);
			if (admin != null) {
				int authority = admin.getAuthority();
				String level = "";
				switch (authority) {
				case 0:
					level = "超级管理员：";
					break;
				case 1:
					level = "高级管理员：";
					break;
				case 2:
					level = "普通管理员：";
					break;
				}
				this.writeReturnMsg("{'success':true, 'level':'" + level
						+ "', 'realName':'" + admin.getRealName() + "'}");
			}
		} catch (ApplicationException e) {
			this.writeReturnMsg("{'success':false, 'msg':'" + e.getMessage()
					+ "' , 'type':'error'}");
		}
		return null;
	}

	/** 后台分页返回管理员列表 **/
	public String adminManage() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(ServletActionContext.HTTP_REQUEST);
		String pageStr = request.getParameter("page");
		String findPara = request.getParameter("findPara");
		int pageIndex = 1;
		if (!RefParaValue.empty(pageStr)) {
			pageIndex = Integer.parseInt(pageStr);
		}
		if (RefParaValue.empty(findPara)) {
			findPara = "";
		}
		Page page = new Page(pageIndex, 29); // 每页显示29条记录（刚好）
		List<?> list = null;
		list = adminLogic.findAdminList(page, findPara);
		request.setAttribute("page", page);
		request.setAttribute("list", list);
		return Action.SUCCESS;
	}

	/** 验证忘记密码请求信息 **/
	public void validateForgetPass() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(ServletActionContext.HTTP_REQUEST);
		String validateImage = request.getParameter("validate");
		if (!RefParaValue.empty(validateImage)) {
			String validateImageVar = validateImage.toLowerCase();
			String randVar = String.valueOf(ctx.getSession().get("rand"))
					.toLowerCase();
			if (!validateImageVar.equals(randVar)) {
				this.addFieldError("tipImage", "验证码错误！");
			}
		}
	}

	/** 管理员注销 **/
	public String backlogout() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(ServletActionContext.HTTP_REQUEST);
		AdminBean admin = (AdminBean) request.getSession().getAttribute("user");
		try {
			if (adminLogic.updateLogoutStatus(admin)) {
				request.getSession().removeAttribute("admin");
				request.getSession().invalidate();
			} else {
				return Action.ERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Action.SUCCESS;
	}

	private void writeReturnMsg(String msg) {
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx
				.get(ServletActionContext.HTTP_RESPONSE);
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		try {
			PrintWriter out = response.getWriter();
			out.write(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getname() {
		return name;
	}

	public void setname(String name) {
		this.name = name;
	}

	public String getRePassword() {
		return rePassword;
	}

	public void setRePassword(String rePassword) {
		this.rePassword = rePassword;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public AdminBean getadminBean() {
		return adminBean;
	}

	public void setadminBean(AdminBean adminBean) {
		this.adminBean = adminBean;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRealName() {
		return realName;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public AdminBean getAdminBean() {
		return adminBean;
	}

	public void setAdminBean(AdminBean adminBean) {
		this.adminBean = adminBean;
	}

	public AdminLogic getAdminLogic() {
		return adminLogic;
	}

	public void setAdminLogic(AdminLogic adminLogic) {
		this.adminLogic = adminLogic;
	}

	public Integer getAuthority() {
		return authority;
	}

	public void setAuthority(Integer authority) {
		this.authority = authority;
	}

	public String getNotes() {
		return notes;
	}

	public void setNotes(String notes) {
		this.notes = notes;
	}

}
